import { ref, watch } from 'vue'
import { nameCharacters, nameScoreRules } from '../data/nameCharacters'

export function useNameGeneration() {
  const generatedNames = ref([])
  const favorites = ref([])

  // 从localStorage加载收藏
  const loadFavorites = () => {
    try {
      const saved = localStorage.getItem('name-favorites')
      if (saved) {
        favorites.value = JSON.parse(saved)
      }
    } catch (e) {
      console.error('Error loading favorites:', e)
    }
  }

  // 获取随机字符，避免重复
  const getRandomChar = (chars, excludeChars = []) => {
    const availableChars = chars.filter(char => !excludeChars.includes(char.char))
    return availableChars[Math.floor(Math.random() * availableChars.length)]
  }

  // 计算名字分数
  const calculateScore = (char1, char2) => {
    let score = Math.floor((char1.score + char2.score) / 2)
    
    // 检查字义搭配
    const meaningMatch = checkMeaningMatch(char1.meaning, char2.meaning)
    score += nameScoreRules.meaningMatch[meaningMatch]
    
    // 其他评分规则...
    
    return Math.min(Math.max(score, 60), 100) // 限制分数范围
  }

  // 检查字义搭配
  const checkMeaningMatch = (meaning1, meaning2) => {
    // 简单的字义匹配逻辑
    if (meaning1.includes('高') && meaning2.includes('远')) return 'good'
    if (meaning1.includes('风') && meaning2.includes('骨')) return 'good'
    // 更多字义匹配规则...
    return 'neutral'
  }

  // 生成名字的核心逻辑
  const generateNames = (surname, gender, count = 6) => {
    if (!surname) return []
    
    const chars = nameCharacters[gender]
    const names = []
    const usedChars = new Set()
    const usedCombinations = new Set()

    const candidateCount = count * 2
    for (let i = 0; i < candidateCount; i++) {
      const firstChar = getRandomChar(chars, Array.from(usedChars))
      const secondChar = getRandomChar(chars, [firstChar.char])
      
      const combination = firstChar.char + secondChar.char
      if (usedCombinations.has(combination)) {
        continue
      }
      usedCombinations.add(combination)
      
      const score = calculateScore(firstChar, secondChar)
      
      const fullName = surname + combination
      const isFavorite = favorites.value.some(f => f.fullName === fullName)
      
      names.push({
        characters: combination,
        meaning: `${firstChar.char}: ${firstChar.meaning}\n${secondChar.char}: ${secondChar.meaning}`,
        score,
        isFavorite,
        source: {
          first: firstChar.meaning,
          second: secondChar.meaning
        },
        categories: {
          first: getCharacterCategory(firstChar, gender),
          second: getCharacterCategory(secondChar, gender)
        }
      })
    }

    return names
      .sort((a, b) => b.score - a.score)
      .slice(0, count)
      .map((name, index) => ({
        ...name,
        rank: index + 1
      }))
  }

  // 获取字符的分类
  const getCharacterCategory = (char, gender) => {
    const categories = {
      male: [
        '品德气节', '文雅才华', '志向抱负', '智慧聪慧',
        '力量豪迈', '山水意象', '天文意象'
      ],
      female: [
        '优雅气质', '花卉意象', '才情智慧', '锦绣华彩',
        '美玉珠宝', '自然意象'
      ]
    }

    const meaning = char.meaning.toLowerCase()
    return categories[gender].find(category => 
      meaning.includes(category.toLowerCase())
    ) || '其他'
  }

  // 添加到收藏
  const addToFavorites = (name) => {
    if (!favorites.value.some(f => f.fullName === name.fullName)) {
      favorites.value.push({
        ...name,
        timestamp: Date.now()
      })
      saveFavorites()
    }
  }

  // 从收藏中移除
  const removeFromFavorites = (index) => {
    favorites.value.splice(index, 1)
    saveFavorites()
  }

  // 保存收藏到localStorage
  const saveFavorites = () => {
    try {
      localStorage.setItem('name-favorites', JSON.stringify(favorites.value))
    } catch (e) {
      console.error('Error saving favorites:', e)
    }
  }

  // 监听收藏变化
  watch(favorites, () => {
    saveFavorites()
  }, { deep: true })

  return {
    generatedNames,
    favorites,
    generateNames,
    loadFavorites,
    addToFavorites,
    removeFromFavorites
  }
} 